package com.abc.robot01.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import com.abc.robot01.R
import com.abc.robot01.activity.compose.MyDropdownMenu
import com.abc.robot01.databinding.ContentSolutionBinding
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.retrofit.bean.Item7
import com.abc.robot01.retrofit.bean.Item71
import com.abc.robot01.view.enableHomeClick
import com.abc.robot01.view.enableInfoClick
import com.abc.robot01.view.enableSpClick
import com.abc.robot01.vivemodel.FangAnKuViewModel
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage


/**
 * 方案库
 */
class FangAnKuActivity : BaseVoiceActivity() {
    private val viewModel: FangAnKuViewModel by viewModels()
    private lateinit var binding: ContentSolutionBinding

    override fun handleVoiceCommand(asr: String): Boolean {
        if(asr.contains("商品")) {
            startActivity<ShangPinKuActivity> { }
            finish()
            playTTS("好的")
            return true
        } else
            if(asr.contains("信息")) {
                startActivity<SysMessageActivity> { }
                finish()
                playTTS("好的")
                return true
            }
            else
                if(asr.contains("方案")) {
                    return true
                }
        if(asr.contains("首页")) {
            finish()
            playTTS("好的")
            return true
        }
        return false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate");
        binding = ContentSolutionBinding.inflate(layoutInflater);
        setContentView(binding.root)

        viewModel.loadData2()

        enableSpClick(){
            finish()
            startActivity<ShangPinKuActivity>()
        }

        enableInfoClick(){
            finish()
            startActivity<SysMessageActivity>()
        }

        enableHomeClick(){
            finish()
        }

        binding.composeView.setContent {
            var w by remember { mutableStateOf(0) }
            var showPopup = remember { viewModel.showPopup }

            val show = remember { viewModel.show }
            val selected1 = remember { viewModel.selected10 }

                val items: List<Item71> by viewModel.questionList2.collectAsState()
            LaunchedEffect(viewModel.isPublic.value) {
                viewModel.loadData()
            }
            Box(
                modifier = Modifier.fillMaxSize()
            ) {
                // 背景图片
                Image(
                    painter = painterResource(id = R.drawable.z1), // 替换为你的图片资源ID
                    contentDescription = null,
                    contentScale = ContentScale.Crop, // 使图片填充整个背景
                    modifier = Modifier.matchParentSize() // 使图片铺满整个Box
                )
                Column(
//                modifier = Modifier
//                .padding((30/3.5f).dp)
                ) {
                    Spacer(modifier = Modifier.height(30.px))
                    BasicText(
                        text = "方案库",
                        style = TextStyle(
                            fontWeight = FontWeight.Bold,
                            fontSize = 10.sp,
                            color = MYBLACK
                        ),
                        modifier = Modifier
                            .offset(x = 30.px)
//                        .padding((30 / 3.5f).dp)
//                            .clickable {
//                                Log.e(TAG, "" + 8.sp.value);
//                            }
                    )
                    Spacer(modifier = Modifier.height(30.px))
                    Row {
                        RowWithShapeBox()
                        Spacer(modifier = Modifier.width(15.dp))
                        Column {
                            CustomStyledTextField(
                                placeHolder = "请输入关键词搜索",
                                onValueChange= {str ->
//                                    viewModel.name.value = str
                                    viewModel.loadData3(str)
                                }
                            ) {
                                viewModel.name.value = it
                                viewModel.loadData()
                            }
                            if (show.value) {
                                MyDropdownMenu2(
                                    show, selected1,
                                    selectedCode = viewModel.selectedHouseType,
                                    offsetY = 0.px,
                                    offsetX2 = w,
                                    items2 = items.map {
                                        it.name   to it.id
                                    }
                                ){
                                    viewModel.name.value =it
                                    viewModel.loadData()
                                }
                            }
                        }
                        Spacer(modifier = Modifier.width(26.px))
                        Box(modifier = Modifier
                            .align(Alignment.CenterVertically)
                            .clickable {
                                showPopup.value = showPopup.value.not()
                            }) {
                            Row {
                                BasicText(
                                    modifier = Modifier.align(Alignment.CenterVertically),
                                    text = "更多筛选",
                                    style = TextStyle(
                                        fontSize = MyFont_Size ,
                                        color = MYBLACK
                                    ),
//                        .padding((30 / 3.5f).dp)
//                            .clickable {
//                                Log.e(TAG, "" + 8.sp.value);
//                            }
                                )
                                Spacer(modifier = Modifier.width(10.px))
                                Image(
                                    painter = painterResource(R.drawable.arrow_down), // Replace with your image resource
                                    contentDescription = "Local Image", // Description for accessibility
                                    modifier = Modifier
                                        .align(Alignment.CenterVertically) // Align the image vertically within the row
                                )
                            }
                        }
                        if (showPopup.value) {
                            Popup1(showPopup)
                        }
                    }
                    Spacer(modifier = Modifier.height(30.px))
                    Box(modifier = Modifier.fillMaxSize()){
                        SimpleGrid()
                        if(showPopup.value){
                        Box(modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black.copy(alpha = 0.5f)))
                        }
                    }
                    Spacer(modifier = Modifier.height(30.px))
                }
                val loading = remember { viewModel.loading }
                LoadingDialog(loading)

                if(1==2) {
                    Column {
                        Button(onClick = {
                            w += 1;
                            /*TODO*/
                        }) {
                            Text(text = "add:" + w)
                        }

                        Button(onClick = {
                            w -= 1;
                            /*TODO*/
                        }) {
                            Text(text = "add2:" + w)
                        }
                    }
                }

            }
        }
    }

    @Composable
    fun Popup1(showPopup:MutableState<Boolean>) {
        //喜好
        val selected1 = remember { viewModel.interests }

        //风格
        val selected2 = remember { viewModel.style }

        val selected3 = remember { viewModel.style2 }

        val question = remember { mutableStateOf("") }

        val names1: List<HouseType> by viewModel.question2List.collectAsState()

        val names2: List<HouseType> by viewModel.question3List.collectAsState()

        val names3: List<HouseType> by viewModel.question4List.collectAsState()

        val expanded2 = remember { viewModel.expanded2 }
        val selected20 = remember {viewModel.selected20}

        Popup(
            properties = PopupProperties(focusable = true),
            alignment= Alignment.TopStart,
            offset =  IntOffset(1*30, 50),
            onDismissRequest = {
                showPopup.value = false
            }) {
            Card(modifier = Modifier.size( (1026).dp/3.5f,(450).dp/3.5f),
                shape = RoundedCornerShape(40.px),
                colors =  CardDefaults.cardColors(containerColor = Color.White)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(Color.Transparent)
                        .offset(y = 30.px, x = 30.px))
                {
                    Row(verticalAlignment=Alignment.CenterVertically, modifier = Modifier.background(Color.Transparent)) {
                        Spacer(modifier = Modifier.width(48.px))
                        Text(text = "喜好", fontSize = MyFont_Size)
                        names1.forEach {
                            Spacer(modifier = Modifier.width(6.dp))
                            TwoStateButton(selected1, it.name){ name ->
//                                Log.e(TAG, "TwoStateButton onClick :${ viewModel.interests.value}")
                                viewModel.interestsCode.value=it.code
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(20.px))
                    Row(verticalAlignment=Alignment.CenterVertically,modifier = Modifier.background(Color.Transparent)) {
//                        Spacer(modifier = Modifier.width(14.dp))
                        Text(text = "选择户型", fontSize = MyFont_Size)
                        names2.forEach {
                            Spacer(modifier = Modifier.width(6.dp))
                            TwoStateButton(selected3,"${it.name}"){
                                name->
                                viewModel.styleCode2.value=it.code
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(20.px))

                    Row(verticalAlignment=Alignment.CenterVertically,modifier = Modifier.background(Color.Transparent)) {
                        Spacer(modifier = Modifier.width(48.px))
                        Text(text = "风格", fontSize = MyFont_Size)
                        names3.subList(0,5).forEach {
                            Spacer(modifier = Modifier.width(6.dp))
                            TwoStateButton(selected2,"${it.name}"){ name ->
                                viewModel.styleCode.value=it.code
                            }
                        }
                    }

                    if(names3.size > 5){
                        Spacer(modifier = Modifier.height(20.px))
                        Row(verticalAlignment=Alignment.CenterVertically,modifier = Modifier.background(Color.Transparent)) {
                            Spacer(modifier = Modifier.width(94.px))
                            names3.subList(5,names3.size).forEach {
                                Spacer(modifier = Modifier.width(6.dp))
                                TwoStateButton(selected2,"${it.name}"){ name ->
                                    viewModel.styleCode.value=it.code
                                }
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(20.px))

                    Row(verticalAlignment=Alignment.CenterVertically,modifier = Modifier.background(Color.Transparent)) {
                        Text(text = "硬装标准", fontSize = MyFont_Size)
                        Spacer(modifier = Modifier.width(20.px))

                        Column {
                            CustomStyledTextField4(selected20,textColor = MYBLACK_Percent5) {
                                expanded2.value = expanded2.value.not()
                            }

                            val items: List<HouseType> by viewModel.question5List.collectAsState()

                            if (expanded2.value) {
                                MyDropdownMenu(expanded2,items=items.map { it.name }, selected = selected20)
                            }
                        }
                    }

              //最底部
                    Row(verticalAlignment=Alignment.CenterVertically,
                        modifier = Modifier
                            .fillMaxWidth()
                            .offset(y = 10.dp)
                            .wrapContentWidth(Alignment.CenterHorizontally)
                    ) {
                        MyButton01(
                            shape = RoundedCornerShape(6.px),
                            text = "重置", containerColor = MYBLACK_Percent10,textColor = Color.Black){
                            viewModel.reset()
//                            viewModel.loadData()
                        }
                        Spacer(modifier = Modifier.width(20.dp))
                        MyButton01(
                            shape = RoundedCornerShape(6.px),
                            text = "确认",containerColor= MYBLUE,textColor=Color.White){
                            showPopup.value = false
                            viewModel.loadData()
                        }
                    }
                }
            }
        }
    }

    /**
     *  公库私库
     */
    @Composable
        fun RowWithShapeBox() {
            // State to keep track of the current image resource
            var isPrivate by remember { mutableStateOf(true) }

            // Define two images to switch between
            val up = painterResource(id = R.drawable.up) // Replace with your first image resource
            val down = painterResource(id = R.drawable.down) // Replace with your second image resource


            Box(
                modifier = Modifier
                    .offset(x = 30.px)
                    .size(314.px, 50.px)
//                    .clickable {
//                        isToggled = !isToggled
//                    }
//                    .padding(16.dp)
                    .background(MYBLACK_Percent5, shape = RoundedCornerShape(25)) // Apply shape with background
            ) {
                Row(modifier = Modifier.align(Alignment.Center)) {
                    MyButton01(text = "私库",size=DpSize(148.px,42.px),textColor = MYBLACK,
                        containerColor = if(isPrivate) Color.White else Color.Transparent,shape = RoundedCornerShape(25)){
                        viewModel.isPublic.value = false
                        isPrivate=true
                    }
                    Spacer(modifier = Modifier.width(10.px))
                    MyButton01(text = "公库",size=DpSize(148.px,42.px),textColor = MYBLACK,
                        containerColor = if(isPrivate.not()) Color.White else Color.Transparent,shape = RoundedCornerShape(25)){
                        isPrivate=false
                        viewModel.isPublic.value = true
                    }
                }
            }
        }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun SimpleGrid() {
        val items: List<Item7> by viewModel.questionList.collectAsState()
        SystemFragmentBackground2(topStart=40.px) {
            if (items.size == 0) {
                Column(
                    modifier = Modifier.fillMaxSize(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    GlideImage(
                        model = R.drawable.empty,
                        contentDescription = "",
                    )
                    Spacer(modifier = Modifier.height(30.px))
                    BasicText(
                        maxLines = 1,
                        overflow = TextOverflow.Clip,
                        text = "暂无数据",
                        style = TextStyle(
                            fontSize = 30.mysp,
                            color = MYBLACK,
                        )
                    )
                }
                return@SystemFragmentBackground2
            }

            LazyVerticalGrid(
                verticalArrangement = Arrangement.spacedBy(30.px), // 可以设置垂直间隔，例如16dp
                horizontalArrangement = Arrangement.spacedBy(20.px), // 水平间隔设置为 20px
                columns = GridCells.Fixed(5), // 2 columns in the grid
                modifier = Modifier
                    .fillMaxSize()
                    .padding(
                        start = 30.px,
                        end = 30.px,
                        top = 30.px,
                        bottom = 30.px
                    )
            ) {
                itemsIndexed(
                    items,
                    key = { index, item -> item.id + item.name + index }) { index, item ->
                    ImageTextCard(item)
                }
            }
        }
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun ImageTextCard(item:Item7) {
        Card(
            colors = androidx.compose.material3.CardDefaults.cardColors(
                containerColor = MYBLACK_Percent5 // 设置背景色为红色
            ),
            shape = RoundedCornerShape(
                topEnd = 10.px,
                topStart = 10.px,
                bottomStart = 14.px,
                bottomEnd = 14.px,
            ),
            modifier = Modifier
                .background(Color.Transparent)
                .width(334.px)
                .height(254.px)
        ) {
            Column(modifier = Modifier
                .align(Alignment.CenterHorizontally)
                .fillMaxSize()
//                .
//                background(
//                    color = MYBLACK_Percent5,
//                    shape = RoundedCornerShape(
//                        topEnd = 10.px,
//                        topStart = 10.px,
//                        bottomStart = 14.px,
//                        bottomEnd = 14.px,
//                    ),
//                )
                ,
                horizontalAlignment = Alignment.CenterHorizontally
                ) {
                GlideImage(
                    model = item.thumbnail,
                    contentDescription ="",
                    modifier = Modifier
                        .background(color = MYBLACK_Percent10, shape = RoundedCornerShape(10.px))
                        .size(344.px, 190.px)
                        .align(Alignment.CenterHorizontally)
                        .clickable {
                            startActivity<FangAnActivity>() {
                                putExtra("designPackageId", item.id)
                                putExtra("id", item.id)
                                putExtra("renderUrl", item.renderUrl)
                            }
                        },
                )
//               Column(
//                   horizontalAlignment = Alignment.CenterHorizontally,
//                   modifier = Modifier.wrapContentHeight().fillMaxSize()
////                   background(color = MYBLACK_Percent5,
////                   shape = RoundedCornerShape(bottomStart = 14.px,bottomEnd = 14.px))
//
//               ) {
                   Spacer(modifier = Modifier.height(20.px))
                Text(text =item.name,
                    fontSize = (24 / 3.5f).sp,
                    color = MYBLACK,
                    textAlign = TextAlign.Center,
                    modifier = Modifier. width(288.px),
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 1
                )
                   Spacer(modifier = Modifier.height(20.px))
//               }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy")
    }

    companion object {
        const val TAG = "FangAnKuActivity"
    }
}
